package com.filldream.fastboot.common.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author RickSun && iFillDream
 * @version 1.0
 * @data 2020-05-15 14:43
 * @description XmlUtil
 */
@Slf4j
public class XmlUtil {

    /**
     * @author RickSun
     * @Description Map转Xml
     **/
    public static String map2Xml(Map<String, String> sortedParams) {
        if (!(sortedParams instanceof TreeMap)) {
            Map<String, String> temp = new TreeMap<>();
            temp.putAll(sortedParams);
            sortedParams = temp;
        }

        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("xml");

        for (Map.Entry<String, String> entry : sortedParams.entrySet()) {
            String k = entry.getKey();
            Object v = entry.getValue();
            if (StringUtils.isBlank(k) || StringUtils.isBlank(v.toString())) {
                continue;
            }
            Element addElement = root.addElement(k);
            addElement.setText(v.toString());

        }

        return document.getRootElement().asXML();
    }

    /**
     * @author RickSun
     * @Description Xml转Map
     **/
    public static Map<String, String> xmlToMap(String xml) {
        Map<String, String> data = new HashMap<String, String>();
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        String FEATURE = null;
        try {

            FEATURE = "http://apache.org/xml/features/disallow-doctype-decl";
            documentBuilderFactory.setFeature(FEATURE, true);

            FEATURE = "http://xml.org/sax/features/external-general-entities";
            documentBuilderFactory.setFeature(FEATURE, false);

            FEATURE = "http://xml.org/sax/features/external-parameter-entities";
            documentBuilderFactory.setFeature(FEATURE, false);

            FEATURE = "http://apache.org/xml/features/nonvalidating/load-external-dtd";
            documentBuilderFactory.setFeature(FEATURE, false);

            documentBuilderFactory.setXIncludeAware(false);
            documentBuilderFactory.setExpandEntityReferences(false);

        } catch (ParserConfigurationException e) {
            log.error("ParserConfigurationException was thrown. The feature '" + FEATURE
                    + "' is probably not supported by your XML processor.");

        }
        try {
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            InputStream stream = new ByteArrayInputStream(xml.getBytes("UTF-8"));
            org.w3c.dom.Document doc = documentBuilder.parse(stream);
            doc.getDocumentElement().normalize();
            NodeList nodeList = doc.getDocumentElement().getChildNodes();
            for (int idx = 0; idx < nodeList.getLength(); ++idx) {
                Node node = nodeList.item(idx);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    org.w3c.dom.Element element = (org.w3c.dom.Element) node;
                    data.put(element.getNodeName(), element.getTextContent());
                }
            }
            try {
                stream.close();
            } catch (Exception ex) {

            }
        } catch (Exception ex) {

        }
        return data;
    }

}
